import React, { useEffect, useState } from "react";
import { Divider, Upload, message } from 'antd';
import ContentTop from '../../../components/ContentTop';
import { getAccountinfo, avatarUpload } from "../../../api/account";
import '../../../index.scss';

// 导入修改的方法 和hooks 修改数据
import { useDispatch } from "react-redux";
// 导入修改数据方法
import { setUserAvatar } from '../../../store/modules/userSlice'

export default function AccountCenter() {
    const [userInfo, setUserInfo] = useState({});
    const [avatarUrl, setAvatarUrl] = useState("");
    const [userId, setUserId] = useState("");

    //拿到可以调用修改方法的派发对象
    const dispatch = useDispatch();

    useEffect(() => {
        const fetchUserInfo = async () => {
            const user = localStorage.getItem("user");
            if (user) {
                const { id } = JSON.parse(user);
                const res = await getAccountinfo({ id });

                if (res && res.data) {
                    const { accountInfo } = res.data;
                    setUserInfo(accountInfo);
                    setAvatarUrl(`http://8.137.157.16:9002${accountInfo.imgUrl}`);
                    setUserId(id);
                }
            }
        };
        fetchUserInfo();
    }, []);


    const handleChange = async ({ file }) => {
        console.log(file);
        const formData = new FormData();
        formData.append('file', file);
        const res1 = await avatarUpload({ id: userId }, formData);
        if (res1.data.code == 0) {
            message.success(res1.data.msg);
            setAvatarUrl(`http://8.137.157.16:9002${res1.data.imgUrl}`);
            dispatch(setUserAvatar(res1.data.imgUrl))
        }else{
            message.error(res1.data.msg);
        }
    }

    return (
        <div className="app-content">
            <ContentTop>
                <div className="title">
                    个人中心
                </div>
            </ContentTop>

            <div className="content-info">
                <span>管理员ID：{userInfo.id}</span>
                <Divider />
                <span>账号：{userInfo.account}</span>
                <Divider />
                <span>用户组：{userInfo.userGroup}</span>
                <Divider />
                <span>创建时间：{userInfo.ctime ? new Date(userInfo.ctime).toLocaleDateString() : ""}</span>
                <Divider />
                <span>管理员头像：</span><br />

                <Upload
                    accept="image/png, image/jpeg"
                    className="center-upload-style"
                    customRequest={handleChange}
                    showUploadList={false}
                >
                    {avatarUrl && (
                        <img src={avatarUrl} alt="Avatar" style={{ width: 150, height: 150 }} />
                    )}
                </Upload>
            </div>
        </div>
    );
}
